<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索 添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 绑定数据 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mobile" label="手机号码"> </el-table-column>
        <!-- <el-table-column prop="create_time" label="创建日期"> </el-table-column> -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13cd66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                :id="scope.id"
                @click="showEditDialog(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :id="scope.id"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="设置角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                :id="scope.id"
                @click="showSetUserRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 弹出框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%"
    @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <edit-user :show.sync="editDialogVisible" :id.sync="keyId" @getUserList="getUserList"></edit-user>
    <set-user-role-dialog :show.sync="setUserRoleDialogVisible" :role.sync="roleInfo" @getUserList="getUserList"></set-user-role-dialog>
  </div>
</template>

<script>
import EditUser from './EditUser'
import SetUserRoleDialog from './SetUserRoleDialog'

export default {
  name: 'Users',
  components: {
    EditUser,
    SetUserRoleDialog
  },
  data() {
    // 验证邮件
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      console.log('check email')
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('邮箱格式不正确'))
    }
    // 验证手机号
    var checkPhone = (rule, value, callback) => {
      const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      console.log('check phone')
      if (regPhone.test(value)) {
        return callback()
      }
      callback(new Error('手机号码不正确'))
    }
    return {
      // 参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      keyId: 0,
      userList: [],
      total: 0,
      // 控制添加用户对话框
      addDialogVisible: false,
      editDialogVisible: false,
      setUserRoleDialogVisible: false,
      roleInfo: {},
      // 添加用户表单的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {},
      // 表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在 3~10 之间',
            trigger: 'change'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '用户名长度在 6~12 之间',
            trigger: 'change'
          }
        ],
        // email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }],
        // mobile: [{ required: true, message: '请输入手机号码', trigger: 'blur' }]
        mobile: [{ required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      debugger
      // const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.userList = res.data.users
      //   this.pagenum = res.data.pagenum
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged(userinfo) {
      console.log('userStateChanged', userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    addUserDialog() {
      this.addDialogVisible = !this.addDialogVisible
    },
    addDialogClosed() {
      // 监听对话框关闭
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) { return '' }
        // 发送网络请求,添加用户
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        // 刷新数据窗口
        this.getUserList()
      })
    },
    async showEditDialog(scope) {
      console.log('showEditDialog:', this.editDialogVisible)
      this.keyId = scope.id
      console.log('showEditDialog', this.keyId)
      this.editDialogVisible = true
      // const { data: res } = await this.$http.get('users/' + scope.id)
      // if (res.meta.status !== 200) {
      //   this.editDialogVisible = false
      //   return this.$message.error(res.meta.msg)
      // }
      // // debugger
      // this.$message.success(res.meta.msg)
      // this.editDialogVisible = true
      // console.log(res.data)
      // // 保存数据对象到窗口
      // this.editForm = res.data
    },
    closeEditDialog(val) {
      console.log('User parent close...')
      this.editDialogVisible = val
    },
    async editUser(obj) {
      console.log('obj:', obj)
      const { data: res } = await this.$http.put('/users/' + this.editForm.id, {
        email: this.editForm.email, mobile: this.editForm.mobile
      })
      console.log(res)
      if (res.meta.status !== 200) { return this.$message.error(res.meta.msg) }
      this.$message.success(res.meta.msg)
      this.editDialogVisible = false
      this.getUserList()
    },
    async removeUserById(id) {
      console.log('remove id:', id)
      // 询问,如果取消，则使用catch捕捉，并返回err
      const confirmResult = await this.$confirm('删除用户，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      console.log('确认删除')
      const { data: res } = await this.$http.delete('/users/' + id)
      console.log('delete result:', res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // 刷新数据
      this.getUserList()
    },
    showSetUserRoleDialog(row) {
      this.setUserRoleDialogVisible = true
      this.roleInfo = row
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 10px;
}
.box-card {
  margin-top: 10px;
}
.el-table {
  margin-top: 10px;
  border-radius: 3px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 5px;
}
</style>
